<?php
namespace app\admin\controller;
use app\admin\controller\Common;
use app\service\logService;
use app\service\parkingService;
use app\service\roominfoService;
use app\service\orderService;

use think\db\Where;
use think\Exception;
use think\facade\Db;
use think\facade\View;

class Roominfo extends Common{
    //下拉菜单
    public function fetchdata() {
        $type = request()->post('type');
        switch($type) {
            case 1:
                $community_name = request()->post('community_name');
                $group = array_unique((new roominfoService())->groupList($community_name));
                return json($group);
                $group = array_filter($group);
                return array_values($group);
            case 2:
                $community_name = request()->post('community_name');
                $group = request()->post('group');
                $building = array_unique((new roominfoService())->buildingList($community_name,$group));
                sort($building);
                return json($building);
                return $building;
            case 3:
                $community_name = request()->post('community_name');
                $group = request()->post('group');
                $building = request()->post('building');
                $unit = array_unique((new roominfoService())->unitList($community_name,$group,$building));
                sort($unit);
                return json($unit);
                return $unit;
            case 4:
                $community_name = request()->post('community_name');
                $group = request()->post('group');
                $building = request()->post('building');
                $unit = request()->post('unit');
                $room = array_unique((new roominfoService())->roomList($community_name,$group,$building,$unit));
                sort($room);
                return json($room);
                return $room;
            default:
                return json(['info' => '查询错误']);
        }
    }
    //显示小区房屋信息
    public function roominfoList(){
        //根据当前账号查询区域
        //查询当前ID用户类型
        $com = $this->pidTokenId();
        $com['parking_id']=implode(",",$com['parking_id']);
        $whe['id'] = array('in',$com['parking_id']);
        //根据当前账号下的所有区域查询所有停车场
        $parkinglist = (new parkingService())->parkingList($whe);
        View::assign('parkinglist',$parkinglist);
		 //查询停车场ID
        if(!empty($parkinglist)){
            foreach($parkinglist as $park){
                $parkingNo[] = $park['parkingNo'];
            }
            //将数组转换成字符串
            $parkingNo = implode(',',$parkingNo);
        }else{
            $parkingNo = null;
        }
        //$community_id = implode(',',$com['community_id']);
		$communitylist=Db::table("roominfo")->where("parkingNo","in",$parkingNo)->distinct(true)->field('community_name')->select();
        View::assign("communitylist",$communitylist);
        //查询
        $data = request()->get();
        if (!empty($data['community_name'])){
            $groups = array_unique((new roominfoService())->groupList($data['community_name']));
            View::assign('groups', array_values($groups));
                if (empty($data['group'])) {
                    $data['group'] = '';
                }       
                $buildings = array_unique((new roominfoService())->buildingList($data['community_name'],$data['group']));
                sort($buildings);
                View::assign('buildings',$buildings);
                if (!empty($data['building'])) {
                    $units = array_unique((new roominfoService())->unitList($data['community_name'], $data['group'],$data['building']));
                    sort($units);
                    View::assign('units',$units);
                    if(!empty($data['unit'])){
                        $rooms = array_unique((new roominfoService())->roomList($data['community_name'], $data['group'],$data['building'],$data['unit']));
                        sort($rooms);
                        View::assign('rooms',$rooms);
                    }
                }
        }
        
        $where=array();
        if (!empty($data)){
            if(!empty($data['community_name'])){
                $where['community_name'] = $data['community_name'];//小区名称
            }
            
            if(!empty($data['group'])){
                $where['group'] = $data['group'];//组团
            }
            if(!empty($data['building'])){
                $where['building'] = $data['building'];//楼栋
            }
            if(!empty($data['unit'])){
                $where['unit'] = $data['unit'];//单元
            }
            if(!empty($data['room'])){
                $where['room'] = $data['room'];//房号
            }
            if(!empty($data['owner_name'])){
                //$where['owner_name'] = $data['owner_name'];//姓名
                $where[] =['owner_name','like','%'.$data['owner_name'].'%'] ;//姓名
            }
            if(!empty($data['owner_phone'])){
                $where['phone'] = $data['owner_phone'];//电话
            }
            if(!empty($data['user_id'])){
                $where['user_id'] = $data['user_id'];
            }
            if(isset($data['user_id'])&&($data['user_id']=="0")){
                $where['user_id'] = $data['user_id'];
            }

            View::assign('where',$where);
            //$where = array_filter($where);
        }
        $export = $where;
        $export = json_encode($export);
        $export = str_replace("\"","|",$export);
        View::assign('export',$export);
        $page = request()->has('page') ? request()->get('page') : 1;
        //查询房屋条数
        
        $number = (new roominfoService())->roomWhereNumber($parkingNo,$where);

        View::assign('number',$number);
        //查询房屋信息
        $roomlist = (new roominfoService())->roomWhereList($parkingNo,$page,$where);
        //判断是否有数据
        $list = [];
        foreach ($roomlist as $info){

            $car_welfare_order["in_year"]=date("Y",time());
            $car_welfare_order["in_month"]=date("m",time());
            $car_welfare_order["halfyear"]=1;
            if($car_welfare_order["in_month"]>6){
                $car_welfare_order["halfyear"]=2;
            }

            $time=Db::table("car_welfare_order")
                ->where("room_id",$info["id"])
                ->where("in_year",$car_welfare_order["in_year"])
                ->where("halfyear",$car_welfare_order["halfyear"])
                ->where("pstatus",1)
                ->sum("fee_duration");
            //$info["feetime"] = ctime($time);
            //查询房屋是否绑定
            $res=Db::table("userinfo")->where("room_id",$info["id"])->find();
            if(empty($res)){
                $info["bindStatus"] =false;
            }else{
                $info["bindStatus"] =true;
            }
            $info["feetime"] =0;
            $list[] = $info;
        }
        View::assign('list',$list);
        View::assign('roomlist',$roomlist);
        foreach ($data as $k => $v) {
            View::assign($k, $v);
        }
        return View::fetch('roominfo_list');
    }

    //添加小区房屋信息
    public function roominfoAdd(){
        //查询当前ID用户类型
        $com = $this->pidTokenId();
        $com['parking_id']=implode(",",$com['parking_id']);
        $whe['id'] = array('in',$com['parking_id']);
        //根据当前账号下的所有区域查询所有停车场
        $parkinglist = (new parkingService())->parkingList($whe);
        View::assign('parkinglist',$parkinglist);
		 //查询停车场ID
        if(!empty($parkinglist)){
            foreach($parkinglist as $park){
                $parkingNo[] = $park['parkingNo'];
            }
            //将数组转换成字符串
            $parkingNo = implode(',',$parkingNo);
        }else{
            $parkingNo = null;
        }
		
		$communitylist=Db::table("roominfo")->distinct(true)->field('community_name')->select();
        View::assign("communitylist",$communitylist);

        if(request()->isPost()){
            //获取表单数据
            $data = request()->post();
			
			$data["parkingName"]=(new orderService())->parkingIdName($data["parkingNo"]);
            $result = (new roominfoService())->roominfoAdd($data);
            //判断数据是否插入成功
            if($result){
                return "添加成功";
                $this->success('添加房屋成功',url('roominfoAdd'));
            }else{
                $this->error('添加房屋失败',url('roominfoAdd'));
            }
        }else{
            return View::fetch('roominfo_add');
        }
    }

    //修改小区房屋信息
    public function roominfoEdit(){
        //查询小区信息
        $com = $this->pidTokenId();
        //$where['community_id'] = array('in',$com['community_id']);
        
        
        if(request()->isGet()){
            if(!request()->has('id') || empty(request()->param('id'))){
                $this->error('房屋ID错误');
            }
            $id = request()->param('id');
            //查询房屋数据
            $info = (new roominfoService())->roominfoIdList($id);
            View::assign('info',$info);
            return View::fetch('roominfo_edit');
        }else{
            //获取表单数据
            $data = request()->post();
           
            //将修改的数据插入数据库
            $result = (new roominfoService())->roominfoEdit($data);
            //判断数据是否插入成功
            if($result){
				//Db::table("car_multi")->where("room_id",$data["id"])->update(["phone"=>$data["phone"],"owner_name"=>$data["owner_name"]]);
                $this->success('修改房屋信息成功',url('roominfolist'));
            }else{
                $this->error('修改房屋信息失败',url('roominfoEdit'));
            }
        }
    }
    public function roominfoDelId(){
        $id=request()->get("id");

        $roominfo=Db::name('roominfo')->where('id', $id)->find();
        $userList=Db::table("userinfo")->where("room_id",$roominfo["id"])->select();
        $carList=Db::table("car")->where("room_id",$roominfo["id"])->select();
        try {
            Db::startTrans();
            $result = (new roominfoService())->deleteRoomInfo($id);
            (new logService())->deleteRoom($roominfo,"1",session("id"),session("name"));
            foreach ($userList as $userinfo) {
                (new logService())->deleteUser($userinfo,$roominfo["parkingNo"],"1",session("id"),session("name"));
            }
            foreach ($carList as $value){
                (new logService())->deleteCar($value,"1",session("id"),session("name"),"用户删除房号");
            }
            Db::commit();
        }catch (Exception $e){
            Db::rollback();
            $this->error($e->getMessage());
            return ;
        }


        if($result){
            $this->success("删除房屋成功");
        }else{
            $this->error("删除房屋失败");
        }

    }
    //删除房屋信息
    public function roominfoDel(){
        //判断是否存在该数据
        $id = explode(',',request()->param('id'));
        $info = (new roominfoService())->checkRoomInfo($id);
        if (count($info) != count($id)) {
            return json(['error' => '房屋信息不完整']);
        }
        foreach($info as $inf){
            if($inf['status'] == 2){
                $result = (new roominfoService())->deleteRoomInfo($inf['id']);
                if(empty($result)){
                    return json(['error' => '房屋删除失败']); 
                }
            }else{
                //根据传递的ID查询token
                $token = (new roominfoService())->roominfoToken($inf['id']);
                if($token){
                    //将数据传入api
                    $api = new apiService(config('app')['delroom'], 'https://openapi.alipay.com/gateway.do');
                    $res = $api->delRoom(json_encode(['batch_id' => $inf['batch_id'], 'community_id' =>  $inf['community_id'], 'out_room_id' => $inf['out_room_id'],'token' => $token]));
                    if(isset($res['success'])){
                        $result = (new roominfoService())->deleteRoomInfo($inf['id']);
                        if(empty($result)){
                            return json(['error' => '房屋删除失败']); 
                        }
                    }else{
                        return json(['error' => $res['error']]);
                    }
                }else{
                    return json(['error' => '房屋信息不完整']); 
                }
            }
        }
        return json(['info' => '删除成功']);
    }
    
    //通过Excel批量添加房屋信息 
    public function roomExcel(){
        if(request()->isPOST()){
            //上传excel文件
            $file = request()->file('myfile');
            //移到/public/excel/下
            $info = $file->move(ROOT_PATH.'public'.DS.'excel');
            //上传文件成功
            if ($info) {
                //引入PHPExcel类
                vendor('PHPExcel.PHPExcel.Reader.Excel2007');
                //获取上传后的文件名
                $fileName = $info->getSaveName();
                //文件路径\public\excel
                $filePath = 'C:\phpStudy\PHPTutorial\WWW\huiwang1688\public\excel\\'.$fileName;
                //判断文件格式，实例化相应的PHPExcel类，读取excel文件
                $extension = strtolower( pathinfo($fileName, PATHINFO_EXTENSION));
                if ($extension =='xlsx' || $extension =='xls') {
                    $objReader = new \PHPExcel_Reader_Excel2007();
                    $objPHPExcel = $objReader ->load($filePath);
                } else if ($extension=='csv') {
                    $objReader = new \PHPExcel_Reader_CSV();
                    //默认输入字符集
                    $objReader->setInputEncoding('GBK');
                    //默认的分隔符
                    $objReader->setDelimiter(',');
                    //载入文件
                    $objPHPExcel = $objReader ->load($filePath);
                }else{
                    $this->success('文件格式错误',url('billExcel'));
                }  
                //读取excel文件中的第一个工作表
                $sheet = $objPHPExcel->getSheet(0);
                $allRow = $sheet->getHighestRow();  //取得总行数
                //$allColumn = $sheet->getHighestColumn();  //取得总列数
                //从第三行开始插入，第一行是列名
                for ($j=2; $j <= $allRow; $j++) {
					$data["out_parking_id"]=$objPHPExcel->getActiveSheet()->getCell("A".$j)->getValue();//停车场id名称
                    $data["parking_name"] = $objPHPExcel->getActiveSheet()->getCell("B".$j)->getValue();//停车场名称
                    $data['community_name'] = $objPHPExcel->getActiveSheet()->getCell("C".$j)->getValue();//小区
                    $data['group'] = $objPHPExcel->getActiveSheet()->getCell("D".$j)->getValue();//组团
                    $data['building'] = $objPHPExcel->getActiveSheet()->getCell("E".$j)->getValue();//楼栋
                    $data['unit'] = $objPHPExcel->getActiveSheet()->getCell("F".$j)->getValue();//单元
                    $data['room'] = $objPHPExcel->getActiveSheet()->getCell("G".$j)->getValue();//房号
                    
                    $data['owner_name'] = $objPHPExcel->getActiveSheet()->getCell("H".$j)->getValue();//业主姓名
                    $data['phone'] = $objPHPExcel->getActiveSheet()->getCell("I".$j)->getValue();//业主电话
					
					$parkinglotinfo=Db::table("parkinglotinfo")->where("out_parking_id",$data["out_parking_id"])->find();
					if(empty($parkinglotinfo)){
						echo "停车场id错误";die;
					}
					if($parkinglotinfo["parking_name"]!=$data["parking_name"]){
						echo "停车场id与停车场名称不匹配";die;
					}
                    $data = array_filter($data);
                    $number = count($data);
                    $numbers = 9;
                    if( $number >= $numbers){
                        //判断房屋是否重复
                        $comaddress = (new roominfoService())->roomComAddress($data['community_name'],$data['group'],$data['building'],$data["unit"],$data["room"]);
                        if($comaddress){
                            echo "第".$j."行房间号重复，导入失败！<br/>";
                        }else{
                            $last_id = (new roominfoService())->roomExcelAdd($data); 
                            //判断数据是否插入成功
                            if ($last_id) {
                                echo "第".$j."行导入成功，房屋表第:".$last_id."条！<br/>";
                            }else{
                                echo "第".$j."行导入失败！<br/>";
                            } 
                        }
                    }else{
                        echo "第".$j."行数据不完整，导入失败！<br/>";
                    }
                }
            }else{
                $this->success('上传文件失败',url('roomExcel'));
            }
        }else{
            return $this->fetch('room_excel');
        }
    }

    //导出房屋到Excel
    public function roomExportExcel(){
        //获取账单数据
        $id = request()->param('id');
        $export = request()->param('export');
        $export = str_replace("|","\"",$export);
        if(!empty($id)){
            $id = explode(',',request()->param('id'));
            $roomlist = (new roominfoService())->checkRoomInfo($id);
            if(count($roomlist) != count($id)){
                return json(['error' => '房屋信息不完整']);
            }
        }else{
            //查询小区信息
            $com = $this->pidTokenId();
            $whe['community_id'] = array('in',$com['community_id']);
            $communitylist = (new roominfoService())->communityList($whe);
            $community_id = $com['community_id'];
            $where = json_decode($export,true);
            $roomlist = (new roominfoService())->roomWhereNumber($community_id,$where);
            if(empty($roomlist)){
                return json(['error' => '没有账单数据']);
            }
        }
        //设置表头
        //引入PHPExcel类
        vendor('PHPExcel.PHPExcel.Reader.Excel2007');
        $objPHPExcel = new \PHPExcel();
        //设置表头
        $objPHPExcel->setActiveSheetIndex(0)
        ->setCellValue('A1', '支付宝房屋ID')
        ->setCellValue('B1', '小区名称')
        ->setCellValue('C1', '组团')
        ->setCellValue('D1', '楼栋')
        ->setCellValue('E1', '单元')
        ->setCellValue('F1', '房号')
        ->setCellValue('G1', '完整门牌号')
        ->setCellValue('H1', '业主姓名')
        ->setCellValue('I1', '业主电话')
        ->setCellValue('J1', '状态');

        $count = count($roomlist);  //计算有多少条数据
        for ($i=2; $i <= $count+1; $i++) {
            //根据小区ID查询小区名称
            $commId = $roomlist[$i-2]["community_id"];
            $communityName = (new roominfoService())->communityIdName($commId);
            $objPHPExcel->getActiveSheet()->setCellValue('A' . $i, $roomlist[$i-2]["out_room_id"]);
            $objPHPExcel->getActiveSheet()->setCellValue('B' . $i, $communityName['community_name']);
            $objPHPExcel->getActiveSheet()->setCellValue('C' . $i, $roomlist[$i-2]["group"]);
            $objPHPExcel->getActiveSheet()->setCellValue('D' . $i, $roomlist[$i-2]["building"]);
            $objPHPExcel->getActiveSheet()->setCellValue('E' . $i, $roomlist[$i-2]["unit"]);
            $objPHPExcel->getActiveSheet()->setCellValue('F' . $i, $roomlist[$i-2]["room"]);
            $objPHPExcel->getActiveSheet()->setCellValue('G' . $i, $roomlist[$i-2]["address"]);
            $objPHPExcel->getActiveSheet()->setCellValue('H' . $i, $roomlist[$i-2]["owner_name"]);
            $objPHPExcel->getActiveSheet()->setCellValue('I' . $i, $roomlist[$i-2]["owner_phone"]);
            if($roomlist[$i-2]["status"] == 1){
                $status = '已同步';
            }elseif($roomlist[$i-2]["status"] == 2){
                $status = '未同步';
            }
            $objPHPExcel->getActiveSheet()->setCellValue('J' . $i, $status);
        }
        $objPHPExcel->getActiveSheet()->setTitle('房屋信息');      //设置sheet的名称
        $objPHPExcel->setActiveSheetIndex(0);                   //设置sheet的起始位置
        $objWriter = \PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');   //通过PHPExcel_IOFactory的写函数将上面数据写出来
        $PHPWriter = \PHPExcel_IOFactory::createWriter( $objPHPExcel,"Excel2007");
        header('Content-Disposition: attachment;filename="房屋信息.xls"');
        header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
        $PHPWriter->save("php://output"); //表示在$path路径下面生成demo.xlsx文件
    }
    
    
}